<template>
  <div class="home-container">
    <h1 class="title">{{ username }}欢迎来到聊天应用</h1>
    <div class="chat-container">
      <div class="user-list">
        <h2 class="subtitle">用户列表</h2>
        <div
          v-for="item in userList"
          :key="item._id"
          class="user-item"
          :class="{ active: chatid === item._id }"
        >
          <p class="username" @click="chat(item)">{{ item.username }}</p>
        </div>
      </div>
      <div class="chat-area">
        <div class="messages" ref="messagesContainer">
          <div v-for="msg in messages" :key="msg._id" class="message">
            <p v-if="msg.senderId === userId" class="right">{{ username }}: {{ msg.content }}</p>
            <p v-else class="left">{{ chatname }}: {{ msg.content }}</p>
          </div>
        </div>
        <div class="bottom">
          <input type="text" v-model="newMsg" @keyup.enter="send" placeholder="输入消息..." />
          <button @click="send" class="send-button">发送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

axios.defaults.baseURL = 'http://127.0.0.1:3000'

const userId = localStorage.getItem('userId')
const username = localStorage.getItem('username')

// State variables
let userList = ref([])
let messages = ref([])
let chatid = ref('')
let chatname = ref('')
let newMsg = ref('')

// WebSocket connection
const socket = new WebSocket('ws://127.0.0.1:3001')

// Lifecycle hook
onMounted(async () => {
  await getUsers()
  if (userList.value.length > 0) {
    await chat(userList.value[0]) // 自动打开第一个用户的聊天框
  }
  scrollToBottom() // 确保在加载时滚动到最底部
  
  // WebSocket message handler
  socket.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    if (msg.receiverId === userId || msg.senderId === userId) {
      messages.value.push(msg)
      scrollToBottom() // 新消息时滚动到底部
    }
  }
})

// API calls
const getUsers = async () => {
  try {
    const { data: { list, code } } = await axios.get('/users', { params: { userId } })
    if (code === 200) {
      userList.value = list
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const getHistoryMessages = async (receiverId) => {
  try {
    const response = await axios.get(`/messages/history`, {
      params: { receiverId, senderId: userId }
    })
    if (response.data.code === 200) {
      messages.value = response.data.messages
    }
  } catch (error) {
    console.error('获取历史消息失败:', error)
  }
}

// Chat function
const chat = async (item) => {
  chatid.value = item._id
  chatname.value = item.username
  await getHistoryMessages(item._id)
  scrollToBottom() // 切换聊天时滚动到底部
}

// Send message function
const send = () => {
  if (newMsg.value.trim() === '') return

  const message = {
    receiverId: chatid.value,
    senderId: userId,
    content: newMsg.value
  }

  socket.send(JSON.stringify(message))
  messages.value.push(message)
  newMsg.value = ''
  scrollToBottom() // 发送消息后滚动到底部
}

// Scroll to bottom function
const messagesContainer = ref(null)
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.title {
  font-size: 2.2em;
  color: #333;
  margin-bottom: 20px;
  font-weight: bold;
}

.chat-container {
  display: flex;
  width: 100%;
  max-width: 800px;
  height: 80%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.user-list {
  width: 30%;
  max-width: 250px;
  background: #ffffff;
  border-right: 1px solid #e0e0e0;
  padding: 10px;
  overflow-y: auto;
}

.subtitle {
  font-size: 1.5em;
  color: #555;
  margin-bottom: 15px;
  font-weight: 500;
}

.user-item {
  padding: 10px;
  border-radius: 5px;
  transition: background-color 0.3s;
}

.user-item:hover {
  background-color: #e0f7fa;
}

.username {
  font-size: 1.1em;
  color: #333;
  cursor: pointer;
}

.chat-area {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.messages {
  flex-grow: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
  border-radius: 0 0 8px 8px;
  height: 300px;
}

.message {
  margin: 5px 0;
}

.left {
  text-align: left;
  background-color: #e1f5fe;
  padding: 8px;
  border-radius: 10px;
  margin-right: auto;
  max-width: 70%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.right {
  text-align: right;
  background-color: #c8e6c9;
  padding: 8px;
  border-radius: 10px;
  margin-left: auto;
  max-width: 70%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.bottom {
  padding: 10px;
  background-color: #ffffff;
  border-top: 1px solid #e0e0e0;
  display: flex;
}

.bottom input {
  flex-grow: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-right: 10px;
}

.bottom input:focus {
  outline: none;
  border-color: #007aff;
}

.send-button {
  padding: 10px 15px;
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-button:hover {
  background-color: #005bb5;
}
</style>
